package com.ledou44.ledourpc.clienthandler;

import com.alibaba.fastjson.JSON;
import com.ledou44.ledourpc.dto.LedouRpcDTO;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author ledou44
 * 客户端连接服务提供端，获取接口RPC调用结果的主要Handler
 */
public class DefaultClientHandler extends ChannelHandlerAdapter {

    /**
     * 需要发送给客户端的消息
     */
    private final LedouRpcDTO message;

    public DefaultClientHandler(LedouRpcDTO message) {
        this.message = message;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(JSON.toJSONString(message));
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        message.setSuccess(true);
        message.setResult(msg);
        ctx.close();
    }
}
